//
//  GYXMainViewController.swift
//  GYXWeibo
//
//  Created by Twisal on 2016/11/8.
//  Copyright © 2016年 Twisal. All rights reserved.
//

import UIKit
import SVProgressHUD

class GYXMainViewController: UITabBarController {
    fileprivate var timer : Timer?
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 初始化自控制器
        setupChildControllers()
        // 初始化撰写按钮
        setupComposeButton()
        // 初始化时钟
        setupTimer()
        // 设置代理,便于点击首页tabBar按钮时回到起始位置,并刷新
        delegate = self
        
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
        // 添加新特性页面
        setupNewFeatureView()
    }
    
    deinit {
        timer?.invalidate()
        NotificationCenter.default.removeObserver(self)
    }
    
    // 设置设备的方向
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    
    /// 用户登录通知监听
    @objc private func userLogin(note: NSNotification) {
        print("通知消息\(note)")
        // FIXME: 过期或者为空时循环自动登录
        var when = DispatchTime.now()
        // 如果note.object有值,证明token过期,需要重新登录
        if note.object != nil {
            SVProgressHUD.setDefaultMaskType(.gradient)
            SVProgressHUD.showInfo(withStatus: "访问令牌已过期, 请重新登录")
            when = DispatchTime.now() + 2
        }
        
        DispatchQueue.main.asyncAfter(deadline: when) { 
            SVProgressHUD.setDefaultMaskType(.clear)
            let nav = UINavigationController(rootViewController: GYXOAuthViewController())
            self.present(nav, animated: true, completion: nil)
        }
        
    }
    
    /// 撰写微博
    @objc fileprivate func composeStatus() {
        print("撰写微博")
        let v = ComposeTypeView.composeTypeView()
//        view.addSubview(v)
        v.show { [weak v] (clsName) in
            guard let clsName = clsName,
            let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? GYXComposeViewController.Type
            else {
                v?.removeFromSuperview()
                return
            }
            // 初始化获取的控制器
            let vc = cls.init()
            // 包装导航控制器
            let nav = UINavigationController(rootViewController: vc)
            // 展示
            self.present(nav, animated: true) {
                v?.removeFromSuperview()
            }
        }
    }
    
    /// 撰写button
    fileprivate lazy var composeBtn:UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
}


// MARK: - 初始化
extension GYXMainViewController {
    
    
    /// 初始化撰写按钮
    fileprivate func setupComposeButton() {
        tabBar.addSubview(composeBtn)
        let count = CGFloat(viewControllers!.count)
        let w = tabBar.bounds.width / count - 1
        composeBtn.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        composeBtn.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
        
    }
    
    /// 初始化所有子控制器
    fileprivate func setupChildControllers() {
        // 1, 获取沙盒路径
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
        
        // 2, 从沙盒中获取json文件
        var data = NSData(contentsOfFile: jsonPath)
        if data == nil {
            let jsonFile = Bundle.main.path(forResource: "main.json", ofType: nil)
            data = NSData(contentsOfFile: jsonFile!)
        }
        
        guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String : AnyObject]]
            else {
                return
        }

        
        
//        guard let jsonFile = Bundle.main.path(forResource: "main.json", ofType: nil),
//            let data = NSData(contentsOfFile: jsonFile),
//            let array = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [[String : AnyObject]]
//            else {
//                return
//        }
        
/*********************使用固定的数组************************/
//        let array = [
//            ["clsName": "GYXHomeViewController", "title":"首页", "imageName": "home", "visitorDict":["visitorImageName": "", "visitorMessage": "关注一些人,回这里看看有什么惊喜"]],
//            ["clsName": "GYXMessageViewController", "title":"消息", "imageName": "message_center", "visitorDict":["visitorImageName": "visitordiscover_image_message", "visitorMessage": "关注一些人,回这里看看有什么惊喜,关注一些人,回这里看看有什么惊喜关注一些人,回这里看看有什么惊喜"]],
//            ["clsName": "UIViewController"],
//            ["clsName": "GYXDiscoverViewController", "title":"发现", "imageName": "discover", "visitorDict":["visitorImageName": "visitordiscover_image_message", "visitorMessage": "关注一些人,回这里看看有什么惊喜关注一些人,回这里看看有什么惊喜"]],
//            ["clsName": "GYXProfileViewController", "title":"我", "imageName": "profile", "visitorDict":["visitorImageName": "visitordiscover_image_profile", "visitorMessage": "关注一些人,回这里看看有什么惊喜关注一些人,回这里看看有什么惊喜关注一些人,回这里看看有什么惊喜关注一些人,回这里看看有什么惊喜"]]
//            ]
        
        
        // 将数组保存为plist格式
//        (array as NSArray).write(toFile: "/Users/twisal/Desktop/jason.plist", atomically: true)
        // 数组 -> json, 保存为.json文件便于加载进文件中
//        let data = try! JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
//        (data as NSData).write(toFile: "/Users/twisal/Desktop/main.json", atomically: true)
/**********************************************************************/
        
        
        // 遍历数组, 循环创建控制器数组
        var arrayM = [UIViewController]()
        for dict in array! {
            let naviVc = setupController(dict: dict as [String : AnyObject])
            arrayM.append(naviVc)
        }
        
        // 设置tabar的子控制器
        viewControllers = arrayM
     }
    
    /// 初始化导航控制器
    ///
    /// - parameter dict: 需要的参数
    ///
    /// - returns: 导航控制器
    private func setupController(dict: [String: AnyObject]) -> UIViewController {
        guard let clsName = dict["clsName"] as? String,
            let title = dict["title"] as? String,
            let imageName = dict["imageName"] as? String,
            let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? GYXBaseViewController.Type,
            let visitorInfo = dict["visitorDict"] as? [String: String]
            else {
            return UIViewController()
        }
        
        let vc = cls.init()
        vc.title = title
        vc.visitorDict = visitorInfo
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.orange], for: .selected)
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 13)], for: .normal)
        let nav = GYXNavigationController(rootViewController: vc)
        return nav
    }
}


// MARK: - 新特性页面
extension GYXMainViewController {
    
    
    /// 初始化新特性页面
    fileprivate func setupNewFeatureView() {
        // 1, 判断是否登录
        if !GYXNetworkManager.shared.userLogon {
            return
        }
        // 2, 判断显示新特性页面还是欢迎页面
        let v = isNewVersion ? GYXNewFeatureView.newFeature() : GYXWelcomeView.welcomeView()
        
        // 4, 添加到主界面
        view.addSubview(v)
    }
    
    
    /// 计算型属性,只会当做getter方法来使用
    private var isNewVersion: Bool {
        // 1, 获取当前版本号
        let currrentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
        print("当前版本号:\(currrentVersion)")
        // 2, 获取沙盒中的版本号
        let path = ("version" as NSString).cz_appendDocumentDir() ?? ""
        let oldVersion = (try? String(contentsOfFile: path)) ?? ""
        print("老版本号:\(oldVersion)")
        // 3, 保存当前版本号到沙盒
        try? currrentVersion.write(toFile: path, atomically: true, encoding: .utf8)
        // 4, 返回比较结果
        return currrentVersion != oldVersion

    }
}


// MARK: - UITabBarControllerDelegate
extension GYXMainViewController: UITabBarControllerDelegate {
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        // 1, 获取childViewController的索引
        let idx = (childViewControllers as NSArray).index(of: viewController)
        if selectedIndex == 0 && idx == selectedIndex {
            print("点击首页")
            // 2, 获取首页的控制器
            let nav = childViewControllers[0] as! UINavigationController
            let vc = nav.childViewControllers[0] as! GYXHomeViewController
            // 3, 设置tableView的滚动范围
            vc.tableView?.setContentOffset(CGPoint(x: 0, y: -64), animated: true)
            // 4, 延迟加载数据
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: { 
                 vc.loadData()
            })
            
            // 5, 去除badgeNumber
            vc.tabBarItem.badgeValue = nil
            UIApplication.shared.applicationIconBadgeNumber = 0
           
        }
        return !(viewController.isMember(of: UIViewController.self))
    }
}

// MARK: - 时钟
extension GYXMainViewController {
    fileprivate func setupTimer() {
        timer = Timer.scheduledTimer(timeInterval: 60.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }
    
    @objc private func updateTimer() {
//        print(#function)
        
        if !GYXNetworkManager.shared.userLogon {
            return
        }
        
        GYXNetworkManager.shared.loadUnreadStatusCount { (count) in
            print("检测到\(count)条未读数据")
            self.tabBar.items?[0].badgeValue = count > 0 ?"\(count)" : nil
            UIApplication.shared.applicationIconBadgeNumber = count
        }
        
    }
}
